<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>集装箱数据BI</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <!-- 集装箱吞吐量 -->
    <div class="gutter-example">
      <a-card title="集装箱吞吐量" :bordered="false" class="work_title">
        <template slot="extra">
          <month-and-year @change="initDateSearch1" />
        </template>
        <div class="gutter-box">
          <a-row :gutter="50">
            <a-col :span="12">
              <div class="iconText">
                <img :src="icon1" alt />
                <span>订单维度</span>
              </div>
              <div class="echarts">
                <div id="echarts1"></div>
                <div class="echarts-label">
                  <div class="item-label" v-for="(v,k) in data1" :key="k">
                    <template v-if="v.name != '暂无数据'">
                      <span class="idot" :style="{'background-color': color[k]}"></span>
                      <span class="name">{{v.name}}</span>
                      <span
                        class="percent"
                      >| {{( total1 === 0 ? 0 : v.value*100 / total1).toFixed(0)}}%</span>
                      <span class="number">{{v.value}} 个</span>
                      <span class="number TEU">{{v.teuQuantity}} TEU</span>
                    </template>
                  </div>
                </div>
              </div>
            </a-col>
            <a-col :span="12" style="border-left:1px solid #e8e8e8;">
              <div class="iconText">
                <img :src="icon2" alt />
                <span>船公司维度</span>
              </div>
              <div class="echarts">
                <div id="echarts2"></div>
                <div class="echarts-label">
                  <div class="item-label" v-for="(v,k) in data2" :key="k">
                    <template v-if="v.name != '暂无数据'">
                      <span class="idot" :style="{'background-color': color[k]}"></span>
                      <a @click="showOrderDetail(v.businessId, 1)" class="name">{{v.name}}</a>
                      <span
                        class="percent"
                      >| {{( total2 === 0 ? 0 : v.value*100 / total2).toFixed(0)}}%</span>
                      <span class="number">{{v.value}} 个</span>
                      <span class="number TEU">{{v.teuQuantity}} TEU</span>
                    </template>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
          <a-divider />
          <a-row :gutter="50">
            <a-col :span="12">
              <div class="iconText">
                <img :src="icon3" alt />
                <span>港口维度</span>
              </div>
              <div class="echarts">
                <div id="echarts3"></div>
                <div class="echarts-label">
                  <div class="item-label" v-for="(v,k) in data3" :key="k">
                    <template v-if="v.name != '暂无数据'">
                      <span class="idot" :style="{'background-color': color[k]}"></span>
                      <a @click="showOrderDetail(v.businessId, 2)" class="name">{{v.name}}</a>
                      <span
                        class="percent"
                      >| {{( total3 === 0 ? 0 : v.value*100 / total3).toFixed(0)}}%</span>
                      <span class="number">{{v.value}} 个</span>
                      <span class="number TEU">{{v.teuQuantity}} TEU</span>
                    </template>
                  </div>
                </div>
              </div>
            </a-col>
            <a-col :span="12" style="border-left:1px solid #e8e8e8;">
              <div class="iconText">
                <img :src="icon4" alt />
                <span>驳船维度</span>
              </div>
              <div class="echarts">
                <div id="echarts4"></div>
                <div class="echarts-label">
                  <div class="item-label" v-for="(v,k) in data4" :key="k">
                    <template v-if="v.name != '暂无数据'">
                      <span class="idot" :style="{'background-color': color[k]}"></span>
                      <span class="name">{{v.name}}</span>
                      <span
                        class="percent"
                      >| {{( total4 === 0 ? 0 : v.value*100 / total4).toFixed(0)}}%</span>
                      <span class="number">{{v.value}} 个</span>
                      <span class="number TEU">{{v.teuQuantity}} TEU</span>
                    </template>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </div>
    <!-- 订单 -->
    <div class="gutter-example">
      <a-card title="订单" :bordered="false" class="work_title">
        <template slot="extra">
          <month-and-year @change="initDateSearch2" style="display:inline-block" />
          <a @click="hrefTZ" style="margin-left:20px">
            查看台账
            <a-icon type="right-circle" style="margin-left:7px" />
          </a>
        </template>
        <div class="gutter-box">
          <a-row>
            <a-col :span="18">
              <div id="orderEcharts"></div>
            </a-col>
            <a-col :span="6">
              <div class="orderItems" :style="{'background': '#CFE8FF'}">
                <div class="order_text">总单量（笔）</div>
                <div class="order_num">{{totalOrderNum}}</div>
              </div>
              <div class="orderItems" :style="{'background': '#C3EDAF',margin:'20px 0'}">
                <div class="order_text">总毛利（元）</div>
                <div class="order_num">{{totalGrossMargin}}</div>
              </div>
              <div class="orderItems" :style="{'background': '#FEE0B9'}">
                <div class="order_text">平均毛利（元/单）</div>
                <div class="order_num">{{averageGrossMargin}}</div>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </div>
    <!-- 运营数据—船舶维度 -->
    <div class="gutter-example">
      <a-card title="运营数据—船舶维度" :bordered="false" class="work_title">
        <template slot="extra">
          <!-- <a-button type="link" ghost @click="currentMonth3">本月</a-button>
          <a-button type="link" ghost @click="currentYear3">全年</a-button>
          <a-range-picker style="width:220px" @change="timeChange3" :value="throughValue3" />-->
          <month-and-year @change="initDateSearch3" style="display:inline-block" />
          <a @click="hrefBB" style="margin-left:20px">
            查看报表
            <a-icon type="right-circle" style="margin-left:7px" />
          </a>
        </template>
        <div class="gutter-box">
          <a-row>
            <a-col :span="18">
              <div id="shipEcharts"></div>
            </a-col>
            <a-col :span="6">
              <div class="orderItems" :style="{'background': '#CFE8FF'}">
                <div class="order_text">总舱位费（元）</div>
                <div class="order_num">{{totalCharge}}</div>
              </div>
              <div class="orderItems" :style="{'background': '#C3EDAF',margin:'20px 0'}">
                <div class="order_text">总运营成本（元）</div>
                <div class="order_num">{{totalCost}}</div>
              </div>
              <div class="orderItems" :style="{'background': '#FEE0B9'}">
                <div class="order_text">箱量（TEU）</div>
                <div class="order_num">{{totalTEU}}</div>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </div>
    <a-modal
      v-model="orderDetailShow"
      title="吞吐量详情"
      :body-style="{padding:'30px'}"
      :footer="null"
      :width="500"
      centered
      destroyOnClose
    >
      <div class="echarts-label" v-if="containerThroughPut.length > 0">
        <div class="item-label" v-for="(v,k) in containerThroughPut" :key="k">
          <span class="idot" :style="{'background-color': color[k]}"></span>
          <span class="name">{{v.name}}</span>
          <span class="percent">|</span>
          <span class="number">{{v.quantity}} 个</span>
          <span class="number TEU">{{v.teuQuantity}} TEU</span>
        </div>
      </div>
      <a-empty v-else />
    </a-modal>
  </div>
</template>
<script>
import { Divider } from 'ant-design-vue'
import MonthAndYear from '@/components/MonthAndYear'
import moment from 'moment'
import { queryContainerThroughPut, queryContainerOrderReport, queryContainerShipReport, queryContainerThroughPutDetail } from '@/api/dataBI'
import icon1 from '@@/images/CDataBi1.png'
import icon2 from '@@/images/CDataBi2.png'
import icon3 from '@@/images/CDataBi3.png'
import icon4 from '@@/images/CDataBi4.png'
const color = [
  '#3AA1FF',
  '#4ECB73',
  '#36CBCB',
  '#FBD437',
  '#F2637B',
  '#975FE4',
  '#F7B35A',
  '#57B0EB',
  '#ABE143',
  '#ED9D68',
  '#3AA1FF',
  '#4ECB73',
  '#36CBCB',
  '#FBD437',
  '#F2637B',
  '#975FE4',
  '#F7B35A',
  '#57B0EB',
  '#ABE143',
  '#ED9D68'
]
export default {
  components: {
    [MonthAndYear.name]: MonthAndYear,
    [Divider.name]: Divider
  },
  data () {
    return {
      color,
      // 集装箱吞吐量
      throughValue: [],
      data1: [],
      total1: 0,
      icon1,
      data2: [],
      total2: 0,
      icon2,
      data3: [],
      total3: 0,
      icon3,
      data4: [],
      total4: 0,
      icon4,
      // 订单
      throughValue2: [],
      totalOrderNum: 0,
      totalGrossMargin: 0,
      averageGrossMargin: 0,
      // 运营数据—船舶维度
      throughValue3: [],
      totalCharge: 0,
      totalCost: 0,
      totalTEU: 0,
      orderDetailShow: false,
      containerThroughPut: []
    }
  },
  methods: {
    // 环形图
    drawPie (target, text, subtext, data, textPosition, fontColor, edageText) {
      // 绘制图表
      target.setOption({
        title: {
          text: text,
          textStyle: {
            color: fontColor ? '#D9001B' : '#666',
            fontWeight: 'normal',
            fontSize: 14
          },
          subtext: subtext === 0 ? '0' : subtext,
          subtextStyle: {
            color: fontColor ? '#D9001B' : '#666',
            fontWeight: 'bold',
            fontSize: textPosition ? 20 : 26
          },
          top: textPosition || '43%',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: function (data) {
            return (
              data.seriesName +
              '<br/>' +
              data.name +
              ' : ' +
              data.value +
              ' (' +
              data.percent.toFixed(0) +
              '%)'
            )
          }
        },
        legend: {
          selectedMode: 'true',
          top: 0,
          left: 10,
          orient: 'vertical',
          textStyle: {
            fontSize: 14,
            color: '#666'
          },
          show: false
        },
        series: [
          {
            name: edageText || '箱量',
            type: 'pie',
            radius: ['70%', '85%'],
            selectedMode: 'single',
            label: {
              show: false,
              position: 'center'
            },
            color: color,
            data: data
          }
        ]
      })
    },
    // 折线图
    drawLine (target, dateArray, orderArray, marginArray, averageArray) {
      // console.log(orderArray)
      // console.log(marginArray)
      // console.log(averageArray)
      target.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['订单量', '总毛利', '平均毛利']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateArray
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '订单量',
            type: 'line',
            // stack: '总量',
            color: color[0],
            data: orderArray
          },
          {
            name: '总毛利',
            type: 'line',
            // stack: '总量',
            color: color[1],
            data: marginArray
          },
          {
            name: '平均毛利',
            type: 'line',
            // stack: '总量',
            color: color[6],
            data: averageArray
          }
        ]
      })
    },
    // 折线面积图
    drawArea (target, shipArray, chargeArray, costArray, teuArray) {
      target.setOption({
        tooltip: {
          trigger: 'axis'
          // axisPointer: {
          //   type: 'cross',
          //   label: {
          //     backgroundColor: '#6a7985'
          //   }
          // }
        },
        legend: {
          data: ['运营成本', '舱位费', '箱量TEU']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLabel: {
              interval: 0,
              rotate: -45
            },
            data: shipArray
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '运营成本',
            type: 'line',
            // stack: '总量',
            areaStyle: {},
            smooth: 1,
            color: color[0],
            data: costArray
          },
          {
            name: '舱位费',
            type: 'line',
            // stack: '总量',
            smooth: 1,
            areaStyle: {},
            color: color[1],
            data: chargeArray
          },
          {
            name: '箱量TEU',
            type: 'line',
            // stack: '总量',
            color: color[6],
            areaStyle: {},
            label: {
              normal: {
                show: true,
                position: 'top'
              }
            },
            data: teuArray
          }
        ]
      })
    },
    // 集装箱吞吐量Request
    containerThroughRequest (e) {
      queryContainerThroughPut(e)
        .then(res => {
          let temData = res.data
          // 订单维度
          let data1 = []
          let total1 = 0
          if (temData.orderList.length > 0) {
            temData.orderList.forEach(v => {
              let newObj = {
                value: v.quantity,
                name: v.name,
                teuQuantity: v.teuQuantity
              }
              data1.push(newObj)
              total1 += v.teuQuantity
            })
          } else {
            total1 = 0
            data1 = [{ value: 0, name: '暂无数据' }]
          }

          this.data1 = data1
          this.total1 = total1
          let echarts1 = this.$echarts.init(
            document.getElementById('echarts1')
          )
          this.drawPie(echarts1, '总吞吐量（TEU）', total1, data1, '40%', '', '订单量')
          // 船公司维度
          let data2 = []
          let total2 = 0
          if (temData.holderList.length > 0) {
            temData.holderList.forEach(v => {
              let newObj = {
                value: v.quantity,
                name: v.name,
                teuQuantity: v.teuQuantity,
                businessId: v.businessId
              }
              data2.push(newObj)
              total2 += v.teuQuantity
            })
          } else {
            total2 = 0
            data2 = [{ value: 0, name: '暂无数据' }]
          }
          this.data2 = data2
          this.total2 = total2
          let echarts2 = this.$echarts.init(
            document.getElementById('echarts2')
          )
          this.drawPie(echarts2, '总吞吐量（TEU）', total2, data2, '40%', '', '订单量')
          // 港口维度
          let data3 = []
          let total3 = 0
          if (temData.portList.length > 0) {
            temData.portList.forEach(v => {
              let newObj = {
                value: v.quantity,
                name: v.name,
                teuQuantity: v.teuQuantity,
                businessId: v.businessId
              }
              data3.push(newObj)
              total3 += v.teuQuantity
            })
          } else {
            total3 = 0
            data3 = [{ value: 0, name: '暂无数据' }]
          }
          this.data3 = data3
          this.total3 = total3
          let echarts3 = this.$echarts.init(
            document.getElementById('echarts3')
          )
          this.drawPie(echarts3, '总吞吐量（TEU）', total3, data3, '40%', '', '订单量')
          // 驳船维度
          let data4 = []
          let total4 = 0
          if (temData.shipList.length > 0) {
            temData.shipList.forEach(v => {
              let newObj = {
                value: v.quantity,
                name: v.name,
                teuQuantity: v.teuQuantity
              }
              data4.push(newObj)
              total4 += v.teuQuantity
            })
          } else {
            total4 = 0
            data4 = [{ value: 0, name: '暂无数据' }]
          }
          this.data4 = data4
          this.total4 = total4
          let echarts4 = this.$echarts.init(
            document.getElementById('echarts4')
          )
          this.drawPie(echarts4, '总吞吐量（TEU）', total4, data4, '40%', '', '订单量')
        })
        .catch(rs => {})
    },
    removethroughInstance () {
      document.getElementById('echarts1').removeAttribute('_echarts_instance_')
      document.getElementById('echarts2').removeAttribute('_echarts_instance_')
      document.getElementById('echarts3').removeAttribute('_echarts_instance_')
      document.getElementById('echarts4').removeAttribute('_echarts_instance_')
    },
    // 订单维度Request
    containerOrderRequest (e) {
      queryContainerOrderReport(e)
        .then(res => {
          // console.log(res.data)
          let dateArray = []
          let orderArray = []
          let marginArray = []
          let averageArray = []
          let totalOrderNum = 0
          let totalGrossMargin = 0
          let averageGrossMargin = 0
          res.data.forEach(v => {
            dateArray.push(v.date)
            orderArray.push(v.orderNum)
            marginArray.push(v.grossMargin)
            averageArray.push(v.averageGrossMargin)
            totalOrderNum += v.orderNum
            totalGrossMargin += v.grossMargin
          })
          if (totalOrderNum > 0) {
            averageGrossMargin = (totalGrossMargin / totalOrderNum).toFixed(2)
          } else {
            averageGrossMargin = '0.00'
          }
          this.totalOrderNum = totalOrderNum
          this.totalGrossMargin = totalGrossMargin
          this.averageGrossMargin = averageGrossMargin
          let orderEcharts = this.$echarts.init(
            document.getElementById('orderEcharts')
          )
          this.drawLine(
            orderEcharts,
            dateArray,
            orderArray,
            marginArray,
            averageArray
          )
        })
        .catch(rs => {})
    },
    removeOrderInstance () {
      document
        .getElementById('orderEcharts')
        .removeAttribute('_echarts_instance_')
    },
    // 运营数据—船舶维度
    containerShipRequest (e) {
      queryContainerShipReport(e)
        .then(res => {
          // // console.log(res.data)
          let shipArray = []
          let chargeArray = []
          let costArray = []
          let teuArray = []
          let totalCharge = 0
          let totalCost = 0
          let totalTEU = 0
          res.data.forEach(v => {
            shipArray.push(v.shipName)
            chargeArray.push(v.spaceCharge)
            costArray.push(v.operatingCost)
            teuArray.push(v.teuQuantity)
            totalCharge += v.spaceCharge
            totalCost += v.operatingCost
            totalTEU += v.teuQuantity
          })
          this.totalCharge = totalCharge.toFixed(2)
          this.totalCost = totalCost.toFixed(2)
          this.totalTEU = totalTEU
          let shipEcharts = this.$echarts.init(
            document.getElementById('shipEcharts')
          )
          this.drawArea(
            shipEcharts,
            shipArray,
            chargeArray,
            costArray,
            teuArray
          )
        })
        .catch(rs => {})
    },
    removeShipInstance () {
      document
        .getElementById('shipEcharts')
        .removeAttribute('_echarts_instance_')
    },
    getMonthStartAndEnd (AddMonthCount) {
      // 起止日期数组
      var startStop = []
      // 获取当前时间
      var currentDate = new Date()
      var month = currentDate.getMonth() + AddMonthCount
      if (month < 0) {
        var n = parseInt(-month / 12)
        month += n * 12
        currentDate.setFullYear(currentDate.getFullYear() - n)
      }
      currentDate = new Date(currentDate.setMonth(month))
      // 获得当前月份0-11
      var currentMonth = currentDate.getMonth()
      // 获得当前年份4位年
      var currentYear = currentDate.getFullYear()
      // 获得上一个月的第一天
      var currentMonthFirstDay = new Date(currentYear, currentMonth, 1)
      // 获得上一月的最后一天
      var currentMonthLastDay = new Date(currentYear, currentMonth + 1, 0)
      // 添加至数组
      startStop.push(this.getDateStr(currentMonthFirstDay))
      startStop.push(this.getDateStr(currentMonthLastDay))
      // 返回
      return startStop
    },
    getDateStr (date) {
      var year = ''
      var month = ''
      var day = ''
      var now = date
      year = '' + now.getFullYear()
      if (now.getMonth() + 1 < 10) {
        month = '0' + (now.getMonth() + 1)
      } else {
        month = '' + (now.getMonth() + 1)
      }
      if (now.getDate() < 10) {
        day = '0' + now.getDate()
      } else {
        day = '' + now.getDate()
      }
      return year + '-' + month + '-' + day
    },
    getFullYear () {
      let fullYear = []
      fullYear.push(`${new Date().getFullYear()}-01-01`)
      fullYear.push(`${new Date().getFullYear()}-12-31`)
      return fullYear
    },
    tabChange (key) {
      this.tabKey = key
      this.quantityRankRequest({
        searchType: key
      })
    },
    // 集装箱吞吐量
    initDateSearch1 (startTime, endTime) {
      this.throughValue = [startTime, endTime]
      if (startTime && endTime) {
        this.removethroughInstance()
        this.containerThroughRequest({
          startDate: startTime,
          endDate: endTime
        })
      }
    },
    // 订单
    initDateSearch2 (startTime, endTime) {
      if (startTime && endTime) {
        this.removeOrderInstance()
        this.containerOrderRequest({
          startDate: startTime,
          endDate: endTime
        })
      }
    },
    hrefTZ () {
      this.$router.push('/dataBI/containerAccount')
    },
    // 运营数据—船舶维度
    initDateSearch3 (startTime, endTime) {
      if (startTime && endTime) {
        this.removeShipInstance()
        this.containerShipRequest({
          startDate: startTime,
          endDate: endTime
        })
      }
    },
    timeChange3 (date, dateString) {
      this.throughValue3 = date
      if (dateString[0] && dateString[1]) {
        this.removeShipInstance()
        this.containerShipRequest({
          startDate: dateString[0],
          endDate: dateString[1]
        })
      }
    },
    currentMonth3 () {
      let thisMonth = this.getMonthStartAndEnd(0)
      this.throughValue3 = [moment(thisMonth[0]), moment(thisMonth[1])]
      this.removeShipInstance()
      this.containerShipRequest({
        startDate: thisMonth[0],
        endDate: thisMonth[1]
      })
    },
    currentYear3 () {
      let thisYear = this.getFullYear()
      this.throughValue3 = [moment(thisYear[0]), moment(thisYear[1])]
      this.removeShipInstance()
      this.containerShipRequest({
        startDate: thisYear[0],
        endDate: thisYear[1]
      })
    },
    hrefBB () {
      this.$router.push('/dataBI/operationReport')
    },
    containerThroughPutDetailRequest (e) {
      queryContainerThroughPutDetail(e).then(res => {
        this.containerThroughPut = res.data
        setTimeout(() => {
          this.orderDetailShow = true
        }, 100)
      })
    },
    showOrderDetail (id, typeId) {
      this.containerThroughPutDetailRequest({
        startDate: this.throughValue[0],
        endDate: this.throughValue[1],
        searchType: typeId,
        businessId: id
      })
    }
  },
  mounted () {
  }
}
</script>
<style scoped>
.gutter-example {
  margin: 24px;
}
.gutter-example >>> .ant-row > div {
  background: transparent;
  border: 0;
}
.gutter-box {
  background: #fff;
  padding: 5px 0;
}
.echarts {
  display: flex;
}
.iconText {
  display: flex;
  align-items: center;
  justify-items: center;
}
.iconText img {
  width: 22px;
  height: 22px;
}
.iconText span {
  color: #333;
  font-size: 14px;
  margin-left: 10px;
}
#echarts1,
#echarts2,
#echarts3,
#echarts4 {
  width: 230px;
  height: 230px;
  margin: 0 auto;
}
.echarts-label {
  flex: 1;
  padding: 20px 0;
  line-height: 35px;
}
.item-label {
  display: flex;
  align-items: center;
  justify-items: center;
  font-size: 14px;
}
.item-label .idot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 12px;
}
.item-label .name {
  color: #666;
  margin-right: 12px;
}
.item-label a.name {
  color: #3aa1ff;
}
.item-label .percent {
  color: #ccc;
  margin-right: 12px;
}
.item-label .number {
  color: #666;
}
.item-label .number.TEU {
  margin-left: 20px;
}
.ant-btn-background-ghost.ant-btn-link {
  color: #1890ff;
  color: #666;
}
.ant-btn-background-ghost.ant-btn-link:hover,
.ant-btn-background-ghost.ant-btn-link:focus {
  color: #40a9ff;
  background-color: transparent;
  border-color: transparent;
}
#orderEcharts,
#shipEcharts {
  width: 100%;
  height: 400px;
}
.orderItems {
  padding: 30px 0 20px 40px;
}
.orderItems .order_text {
  color: #52748c;
}
.orderItems .order_num {
  font-size: 26px;
  margin-top: 5px;
}
</style>
